﻿using KWT.DRG_DIP.API.Infrastructure;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using KWT.DRG_DIP.DTO.Basic.DIPPara;
using KWT.DRG_DIP.DB;
using KWT.DRG_DIP.DO.System;
using KWT.DRG_DIP.PO.Basic;
using Microsoft.EntityFrameworkCore;
using OfficeOpenXml;
using Yitter.IdGenerator;
using KWT.DRG_DIP.Common;

namespace KWT.DRG_DIP.API.Controllers.Basic
{
    /// <summary>
    /// DIP分组标杆管理
    /// </summary>
    [ApiExplorerSettings(GroupName = "basic")]
    public class DIPParaController : BasicControllerBase
    {
        public EFContext ef { get; set; }
        /// <summary>
        /// 添加或编辑
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public OutputResult AddOrUpdate(InAddOrUpdate dto)
        {
            if (string.IsNullOrEmpty(dto.ParaID))
            {
                var para = _mapper.Map<Sys_DIP_Para>(dto);
                para.ParaID = "PR" + snow_id.CreateId().ToString();
                ef.Add(para);
            }
            else
            {
                var para = ef.Find<Sys_DIP_Para>(dto.ParaID);
                if (para == null)
                {
                    return Fail("该项不存在！");
                }
                para.ZGFFBZ = dto.ZGFFBZ;
                para.JMFFBZ = dto.JMFFBZ;
                para.UpdTime = DateTime.Now;
                para.Disease_Code = dto.Disease_Code;
                para.Disease_Type = dto.Disease_Type;
                para.HighMag = dto.HighMag;
                para.LowMag = dto.LowMag;
                para.ZGDZ = dto.ZGDZ;
                para.JMDZ = dto.JMDZ;
                para.Score = dto.Score;
                para.Diag_Code = dto.Diag_Code;
                para.Diag_Name = dto.Diag_Name;
                para.LJFY = dto.LJFY;
                para.LowMag = dto.LowMag;
                para.HighMag = dto.HighMag;
                para.ZYTSBGZ = dto.ZYTSBGZ;
                para.SpecialFlag = dto.SpecialFlag;
                ef.Attach(para);
            }
            var flag = ef.SaveChanges() > 0;
            if (flag)
            {
                string tenantID = HttpContext.Request.Headers["TenantID"];
                RedisHelper.HDel("PolicyEnum-" + tenantID, "DIPPara");
            }
            return Output(flag, "操作成功", "操作失败");
        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public OutputResult PageList(InPageList dto)
        {
            var q = ef.Set<Sys_DIP_Para>().AsQueryable();
            if (!string.IsNullOrEmpty(dto.Disease_Code))
            {
                q = q.Where(x => EF.Functions.Like(x.Disease_Code, $"%{dto.Disease_Code}%"));
            }
            if (!string.IsNullOrEmpty(dto.Diag_Name))
            {
                q = q.Where(x => EF.Functions.Like(x.Diag_Name, $"%{dto.Diag_Name}%"));
            }
            if (!string.IsNullOrEmpty(dto.Oper_Name))
            {
                q = q.Where(x => EF.Functions.Like(x.Oper_Name, $"%{dto.Oper_Name}%"));
            }
            if (!string.IsNullOrEmpty(dto.Disease_Type))
            {
                q = q.Where(x => EF.Functions.Like(x.Disease_Type, $"%{dto.Disease_Type}%"));
            }
            int total = q.Count();
            var list = q.OrderByDescending(x => x.AddTime).AsNoTracking().ToPageList(dto.PageNo, dto.PageSize);
            return Output(true, "", "", new PageList<Sys_DIP_Para>() { Total = total, List = list });
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="paraID"></param>
        /// <returns></returns>
        [HttpGet]
        public OutputResult Del([FromQuery] string[] paraID)
        {
            var flag = ef.Set<Sys_DIP_Para>().Where(x => paraID.Contains(x.ParaID)).ExecuteDelete() > 0;
            if (flag)
            {
                string tenantID = HttpContext.Request.Headers["TenantID"];
                RedisHelper.HDel("PolicyEnum-" + tenantID, "DIPPara");
            }
            return Output(flag, "操作成功", "操作失败");
        }

        /// <summary>
        /// 批量导入
        /// </summary>
        /// <param name="file">excel文件</param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(Output<string>), 200)]
        public OutputResult Import(IFormFile file)
        {
            using var pkg = new ExcelPackage(file.OpenReadStream());
            var worksheet = pkg.Workbook.Worksheets[0];

            var list = worksheet.Dimension.ToCollectionWithMappings(row =>
            {
                var para = new Sys_DIP_Para
                {
                    Disease_Code = row.GetValue<string>("病种编码").Trim(),
                    Disease_Type = row.GetValue<string>("病种类型").Trim(),
                    Diag_Code = row.GetValue<string>("主要诊断编码").Trim(),
                    Diag_Name = row.GetValue<string>("主要诊断名称").Trim(),
                    Oper_Code = row.GetValue<string>("主要操作编码").Trim(),
                    Oper_Name = row.GetValue<string>("主要操作名称").Trim(),
                    Other_Code = row.GetValue<string>("相关操作代码").Trim(),
                    Other_Name = row.GetValue<string>("相关操作名称").Trim(),
                    Score = row.GetValue<decimal>("病种分值"),
                    ZGDZ = row.GetValue<decimal>("职工点值"),
                    JMDZ = row.GetValue<decimal>("居民点值"),
                    ZGFFBZ = row.GetValue<decimal>("职工付费标准"),
                    JMFFBZ = row.GetValue<decimal>("居民付费标准"),
                    LJFY = row.GetValue<decimal>("例均费用"),
                    ZYTSBGZ = row.GetValue<decimal>("住院天数标杆值(天)"),
                    HighMag = row.GetValue<decimal>("高倍率"),
                    LowMag = row.GetValue<decimal>("低倍率"),
                    SpecialFlag = row.GetValue<string>("特殊标签").Trim()
                };
                return para;
            }, options => options.HeaderRow = 0);
            var idGeneratorOptions = new Yitter.IdGenerator.IdGeneratorOptions(1) { SeqBitLength = 10 };
            YitIdHelper.SetIdGenerator(idGeneratorOptions);
            list.ForEach(x =>
            {
                x.ParaID = YitIdHelper.NextId().ToString();
            });
            ef.AddRange(list);
            var flag = ef.SaveChanges() > 0;
            if (flag)
            {
                string tenantID = HttpContext.Request.Headers["TenantID"];
                RedisHelper.HDel("PolicyEnum-" + tenantID, "DIPPara");
            }
            return Output(flag, "操作成功", "操作失败");
        }
    }
}
